<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../libs/vue.js"></script>
    <style>
        .item {
            margin: 20px 0;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="form">
            <div class="item">
                姓名：<input type="text" v-model="stuInfo.name">
            </div>
            <div class="item">
                性别：<input type="text" v-model="stuInfo.sex">
            </div>
            <div class="item">
                手机号：<input type="text" v-model="stuInfo.phone">
            </div>
            <div class="item">
                <button @click="submit">点击提交</button>
            </div>

        </div>
        <table width="400" border="1" cellpadding="10" style="border-collapse: collapse;">
            <tr>
                <th>id</th>
                <th>姓名</th>
                <th>性别</th>
                <th>手机号</th>
                <th>操作</th>
            </tr>
            <tr v-for="(item,index) in arr" :key="item.id">
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{{item.sex}}</td>
                <td>{{item.phone}}</td>
                <td>
                    <button @click="del(index)">删除</button>
                </td>
            </tr>
        </table>
    </div>
    <script>
        // console.log(JSON.parse(localStorage.getItem('arr')))
        let vm = new Vue({
            el: '#app',
            data: {
                stuInfo: {
                    name: '',
                    sex: '',
                    phone: ''
                },
                arr: JSON.parse(localStorage.getItem('arr') || '[]')
            },
            methods: {
                submit() {
                    let id = this.arr.length == 0? 1 : this.arr[this.arr.length - 1].id + 1
                    let obj = {
                        id: id,
                        name: this.stuInfo.name,
                        sex: this.stuInfo.sex,
                        phone: this.stuInfo.phone
                    }
                    this.arr.push(obj)
                    // 存储到localStorage
                    localStorage.setItem('arr',JSON.stringify(this.arr))
                    // 清空数据对象
                    this.stuInfo = {
                        name: '',
                        sex: '',
                        phone: ''
                    }
                },
                del(index) {
                    this.arr.splice(index,1)
                    localStorage.setItem('arr',JSON.stringify(this.arr))
                }
            },
        })
    </script>
</body>

</html>